High energy tools for the internet!

MagicTCP! Version 2.2
Short Documentation

Please send any comments or questions to the following email address: MagicTCP@hotmail.com

Basic Information on socket numbers

MagicTCP can handle 1001 sockets in parallel. Each socket has a unique socket number from 0 to 1000. All other socket numbers are illegal. Socket 0 is automatically created during initialisiation of the control. All others must be created by calling New() or are automatically created, when an incoming connection request is accepted.

The current socket number ist set or determined by the property CurrentSocket. Most properties like "LocalHost", "RemoteHost" or "Linger" are accessed in the context the current socket. Other properties like "IniFile" or "WinsockDescription" are global.

When an event like "OnRead()" for a socket is fired, the CurrentSocket property is temporally set to this sockets number. The event code starts with the correct CurrentSocket.

To create a new socket and connect it to a specific host and port, do the following:

with MagicTCP1 .CurrentSocket = .New() .RemoteHost = "hostname.domain.com" .RemotePort = 4711 if not .Connect() then if not .WouldBlock Msgbox "Connect()-Error: " & .LastErrorText() end if end if end with

 

Properties

Datatype Property Description

Default

Read only?

At run time?

At design time?

String AccessList If specified, determines a blank separeted list of IP adresses or fragments of IP adresses from which connection requests are accepted for the current socket. The IP addresses may contain the '*' wild card character, which stands for 0 to n arbitary characters.

All incoming connection requests from hosts which IP adress do not match one in the specified list are automatically rejected.

If this property is not specified (an empty string), all incoming connection requests are accepted.

Example:

192.168.1.* 140.190.*.* 192.11.127.43

""

 

x

x

Integer Backlog Maximum amount of incoming connection requests which can be queued on a listening socket.

10

 

x

x

BOOLEAN Broadcast Enables broadcasting for the current socket. It works only for UDP-sockets (property Type =2) FALSE   x x
Long BytesToRead The actual number of unread bytes on the current socket.  

x

x

 
Long CurrentSocket Sets or retrieves the number of the current socket (0 to 999).

Each socket has it's own distinct set of properties. All property accesses and method invocations are in the context of the current socket.

A new socket is created by calling the New() method or is automatically supplied by the OnAccept() event

0

 

x

x

String DecryptionKey If specified, any data received on this socket is decrypted by this key. It may not contain binary nulls.

The sending host must also use MagicTCP! and has to specify the same key as EncryptionKey.

(see EncryptionKey)

""      
BOOLEAN DontRoute Disables or enables routing of outgoing data. FALSE   x x
String EncryptionKey If specified, any data sent over this socket is encrypted by this secret key. It may not contain binary nulls.

The key value is case-sensitive! Long keys and the usage of a broad range of characters, increases security. Example:

.EncryptionKey = "{Believe it or NOT! I'm in love& with Madonna! Is-this+a~problem~for= you?}"

Keys which contain at least 32 distinct characters should provide enough security.

To decrypt, the remote host must also use MagicTCP! and specify the same secret key as DecryptionKey.

""   x x
String EOL Specifies the "end of line"-string for successive ReadLine() calls. This string must not be longer than 15 characters.        
String ForwardSocket Determines the number of the socket to which all the data received for the current socket should be forwarded.

Everytime data becomes available for the current socket, it will be automatically forwarded to the specified socket.

This is far more effcient than reading data from the current socket and write it to the destination socket by hand.

The value -1 (this is the default) means, that there should be no data forwarding.

-1
(none)

 

x

 
String Hostname Local hostname  

x

x

x

String IniFile Filename of the current inifile, which is accessed by the methods GetProfileString(), GetProfileInt(), SetProfileString() and SetProfileInt().

The value of the IniFile property is global, hence it is not affected by the CurrentSocket.

magictcp.ini   x x
BOOL KeepAlive Should KeepAlive-Packets be sent? 

FALSE

 

x

x

Long LastError Last Winsock error that occured on the socket.

0 = No error

100xx = Winsock error (see winsock documentation for a list of Winsock errors)

 

x

x

 
String LastErrorText text representation of LastError (see above)

[Same as ErrorText(control.LastError)]

       
BOOL Linger FALSE = Any unsent data is discarded on Close()

TRUE = Socket is closed gracefully

TRUE

 

x

x

String LocalHost If online: IP address or hostname of the local interface

if not online: local IP address or hostname where to listen or to connect

If not sepcified, listening will take place on all local interfaces

""
(all local interfaces)

 

x

x

Long LocalPort If online: local TCP port which is involved

if not online: local TCP port where to listen or to connect. If 0 (Null), a currently unused local port is allocated.

0

 

x

x

BOOL LogEnable Global option which enables or disables logging for all sockets FALSE      
String LogFile Full name of the logfile, into which socket activity is logged. All sockets use the same logfile.

If the file already exists, it is overwritten. Supply "*" if you want MagicTCP to create a unique logfile name for you.

""   x x
BOOL LogHexDump Determines wheter the transfered data should be inclued in the logfile in hexadecimal notation. (global option for all sockets) FALSE   x x
BOOL LogSocket Enables or disables logging for the current socket. Accepted sockets inherit this flag from the listening socket on creation. FALSE   x x
BOOL LogTimestamp Determines wheter all logged events should be prefixed by a timestamp. (global option for all sockets) FALSE   x x
BOOL OnReadEvent Temporally enables or disables firing of the OnRead() event.

If the OnRead() event becomes enabled again and any data has arrived while being disabled, an OnRead() event is fired

TRUE

 

x

 
BOOL Online True if the socket is listening, accepted or connected (ready to read or write data).  

x

x

 
Long PartnerSocket Specifies the socket number of a socket, which is associated with the current socket.

If the current socket is deleted or closed, the assocciated socket will also automatically be closed or delete.

On closing or deletion of the partner socket, it's PartnerSocket property is recursevly handled as described above.

-1
(none)
  x x
Long RcvBuf Size of the receive buffer of the socket

8192

 

x

x

Long ReadTimeout Idle timeout for reading in seconds for the current socket - If no data is read for the specified timeout, an OnReadTimeout() event is fired.

0 if no timeout event should be fired

0   x x
String RegCode Future registration code - For now use in uppercase letters:
MAGICTCP!

""

 

x

x

BOOL ReUseAddr Determines wheter the socket may be bound to a local address/port-combination which is already in use

FALSE

 

x

x

String  RemoteHost If not online: Hostname or Ip address of the socket where to connect to.

If online: Ip address of the remote host.

""

 

x

x

Long RemotePort If not online: TCP port of the remote socket where to connect to.

If online: TCP port of the remote host, where the socket is connect to.

0

 

x

x

Long SndBuf Size of the send buffer of the socket

8192

 

x

x

BOOL TcpNoDelay Detemines wheter data should be sent immediatly or buffered by using the Nagle algorithm

TRUE

  x x
Long Type Set the type of the current socket:
1 = TCP
2 = UDP
1 (TCP)   x x
String WinsockDescription Identification supplied by Winsock.dll  

x

x

x

Long WinsockMaxSockets Maximum Number of sockets supported by Winsock.dll   x x x
String WinsockSystem Status System status supplied by Winsock.dll  

x

x

x

Long WinsockMaxUdpDg Maximum length for UDP packets supported by the Winsock.dll   x x x
Long WriteTimeout Idle timeout for writing in seconds for the current socket - If no data is written for the specified timeout, an OnWriteTimeout event is fired.

0 if no timeout event should be fired.

0   x x
BOOL WouldBlock Indicates that the preceeding method invocation (Connect(), Read(), ReadString(), Write(), WriteString()) could not be fulfilled immediatly.

Same as LastError = 10035

 

x

x

 
Long zzState Arbitary state information associated with the current socket. 0   x  
Long zzType Arbitary state information associated with the current socket. 0   x  
String zzBuffer Arbitary state information associated with the current socket. ""   x  

 

Methods

Method Description
BOOL Bind() Binds the current socket to the IP address and TCP port specified by LocalHost and LocalPort. Because Bind() is implicit invoked on Connect() or Listen(), you usally don't have to call Bind() directly.
BOOL Close() Closes the current socket, but does not delete it
BOOL Connect() Connects the current socket to the endpoint specified by the properties RemoteHost and RemotePort. Return values:

TRUE: Connect() succeeded immediatly. OnConnect() is fired!

FALSE: An error occured. If property .WouldBlock is TRUE (.LastError == 10035), the Connect()-operation is still going on. So this is not a real error.

On successful completion an OnConnect()-event is fired. You can start writing to the socket, as soon as the OnWrite()-event is fired for the first time.

Here's an example:

' Set destination
MagicTCP1.RemoteHost = "www.anywhere.com"
MagicTCP1.RemotePort = 80

' Now connect
if MagicTCP1.Connect() then
	 ' Connect has been immediatly successfully completed.
	 ' OnConnect()-event is fired anyway!
else
 	if MagicTCP1.WouldBlock then
	        ' Connect is still going on. when completeted OnConnect()  is fired
	        ' if an error occurs, an OnError() event will be fired
	else
	        ' Connect is completed, but an error occured
	        MsgBox "Connect-Error: " &
	        MagicTCP1.LastErrorText
	end if
end if

BOOL Delete(SocketId as Integer) Deletes the socket specified by SocketId. If this socket is online, it is closed.
BOOLEAN Forward(ForwardSocket as Long, BiDirect as BOOL) By calling this function you determine, that from now on, any data incoming on the currrent socket should automatically be sent out by the socket with socket number ForwardSocket.

If parameter BiDirect is TRUE, you determine that additionally any data incoming on ForwardSocket should automatically be sent out on the current socket.

In our terminology, this type of operation is called "Forwarding". Because no events are fired (i.e. the ActiveX-container is not involved), data forwarding performs very efficient.

By using forwarding and encryption, virtual private networks (VPN) can be implemented very easy.

This function serves as a shortcut for manipulating the properties ForwardSocket by hand.

String GetHostByAddr(IpAddress as String) Returns the hostname for the specified IP address. An empty string is returned if the operation fails.
String GetHostByAddrEx(IpAddress as String) Returns the IP addres for the specified hostname. An empty string is returned if the operation fails.
String GetHostByName(HostName as String) Returns the hostname and all of it's alias hostnames for the specified IP address. The returned values a seperated by a comma.

An empty string is returned if the operation fails.

String GetHostByNameEx(HostName as String) Returns the IP adresses for the specified hostname as comma separated list.

An empty string is returned if the operation fails.

String GetProfileString(Section as String, Key as String, Default as String) Retrieves the value assocated with the specified section and key from the current inifile determined by the property IniFile. If the value can't be found, the supplied default value is returned instead.

[SECTION]
KEY=VALUE

Long GetProfileLong(Section as String, Key as String, Default as Long) Retrieves the value assocated with the specified section and key from the current inifile determined by the property IniFile. If the value can't be found, the supplied default value is returned instead.
BOOL IsValidSocket(SocketId as Integer) Determines wheter SocketId represents a valid socket number.
String ErrorText(WinsockError as Integer) Returns a text representation for the supplied numeric winsock error code, e.g. EWOULDBLOCK if a WinsockError of 10035 is passed.

If the supplied WinsockError is negative, the actual LastError of the current socket is used instead.

BOOL Listen() Starts listening on the current socket. The local IP address and TCP port are specfied by the properties LocalHost and LocalPort.

Incoming connections requests are automatically accepted. Each time a connection is accepted, an OnAccept() event is fired.

If specified, the property AccessList restricts the IP adresses from which connections are accepted.

BOOL LoadProfile(Profile as String) Loads a set of properties ("profile") into the current socket from the current inifile. The supplied argument Profile specifies the name of the profile.

A profile is represented by a section of an inifile. The name of the section is corresponding to the profile name. The properties to be set are sepcified as key / value pairs. Currently the following properties can be set in a profile: AcceptedHosts, Backlog, BroadCast, DecryptionKey, DontRoute, EncryptionKey, KeepAlive, Linger, LocalHost, LocalPort, RcvBuf, RemoteHost, RemotePort, ReUseAddr, SndBuf, TcpNoDelay, zzBuffer, zzState, zzType

Properties of the current socket, which are not specified by a profile, are not affected by LoadProfile()

Example (Profile TESTHOST):

[TESTHOST]
RemoteHost=www.testhost.com
RemotePort=80
ReUseAddr=FALSE
TcpNoDelay=TRUE

Integer New() Creates a new socket and returns it's socket number. If there are no more socket remaining, -1 is returned.

The current socket is not affected.

Integer Read(Buffer as Variant, BufferLen as Integer) Reads binary data from the current socket into a Byte array. Possible values returned:

-1: An error has occured (check for WouldBlock!)
0: The connection has been closed by the remote host
+n: Number of bytes read (<= Bufferlen)

VB-Example:

Dim Buffer(1 to 512) as Byte ' binary data
Dim BytesRead as Integer

BytesRead = M.Read(Buffer,100) 'Read up to 100 bytes into array Buffer()

BOOL ReadLine(Buffer as String, EOL as BOOL) Reads a line from the current socket up to the line terminater specified by the socket property EOL into Buffer. If a line terminator is found, it is discarded. The line terminator is never returned.

On return, the passed argument EOL will be set to TRUE if a line terminator was found, otherwise false.

Return values:

TRUE = Read operation was successfull.

FALSE = A read error occured.

BOOL ReadFile(Filename as String, MaxLen as Long) This function initiates collecting all data, that will be received on the current socket into a file which name is specified by parameter Filename. If the specified file already exists, it will be overwritten.

Parameter MaxLen determines the maximum number of bytes written to file. If MaxLen is zero, incoming data is written to the file until the remote or the local socket is closed.

The file will be closed, if the maximum number of bytes have been written to the file or the remote or the local socket are closed.

When the maximum number of bytes have been received, the file is closed and an OnFileread()-event is fired.

It returns TRUE, if the operation started sucessfully, otherwise FALSE (i.e. the file could not be opened)

When the operation completes, an OnFileWritten()-event is fired.

BOOL ReadString(Buffer as String) Reads all available data from the current socket into a String. Possible values returned:

FALSE: An error occured (check WouldBlock!)
TRUE: Success (len(Buffer) > 0)

BOOL SetProfileString(Section as String, Key as String, Value as String) Adds/updates the specified string value for the specified section and key in the current inifile determined by the property IniFile.
BOOL SetProfileInt(Section as String, Key as String, Value as Long) Adds/updates the specified long value for the specified section and key in the current inifile determined by the property IniFile.
Integer Write(Buffer as Variant, BufferLen as integer) This function is depracted. For new applications use WriteEx()!

Writes binary data to the current socket. The binary data is passed as a array of bytes. The number of bytes to be written is determined by BufferLen.

Possible values returned:
-1: An error has occured
else: Number of bytes sent.

If none or not all bytes have been sent, wait for the next OnWrite()-event and try again sending the remaining data.

BOOLEAN WriteEx(Buffer as Variant, BufferLen as integer) Writes binary data to the current socket. The binary data is passed as a array of bytes. The number of bytes to be written is determined by BufferLen.

Possible values returned:

TRUE: all data has been written successfully. You can proceed to send more data immediatly.

FALSE: An error occured.
If the property WouldBlock says TRUE (.LastError = 10035), not all data has been written by now. MagicTCP! internally queues any data not sent. When the socket becomes ready again, the remaining data is sent automatically. You dont't have to deal with this, when using WriteEx(). After all remaining data has been written, an OnWrite()-event is fired, so you can proceed to send data to the remote host.

BOOLEAN WriteFile(Filename as String) This function initiates sending out the specified file over the current socket. The file contents are transfered as is, no translation occurs.

It returns TRUE, if the operation started sucessfully, otherwise FALSE (i.e. the file could not be opened)

When the operation completes, an OnFileWritten()-event is fired.

Integer WriteString(Buffer as String) This function is depracted. For new applications use WriteStringEx()!

Same as Write(), but passes the data to be sent as String.

BOOLEAN WriteStringEx(Buffer as String) Same as WriteEx(), but passes the data to be sent as String.

 

Events

During the execution of an event procedure, the CurrentSocket property reflects the socket, for which the event has been fired. After the event procedure terminates, the old value of CurrentSocket is restored.

Event Description
OnAccept(ListenSocket as Integer) If an incoming connection request is sucessfully accepted, an OnAccept() event is fired. The socket number of the newly accepted connection is the CurrentSocket.

ListenSocket specifies the number of the corresponding listen socket which received the connection request and created and accepted that socket.

OnClose() When a socket is gracefully closed by the remote host, an OnClose() event is fired.
OnConnect() When a connection request successfully completes, an OnConnect() event is fired.
OnError(WinsockError as Integer, Func as String) An OnError event is fired, if an asynchronous winsock error occurs on the socket.

The numeric code of detected winsock error and the failed function are passed as arguments. Possible supplied values for Func are "ACCEPT", "CLOSE", "CONNECT", "READ" and "WRITE".

OnFileRead(Filename as String, Success as BOOLEAN) The OnFileRead()-event is fired, if in an ongoing ReadFile() operation, the maximum number of bytes have been read, or an error occured. At this point, the read file is already closed and ready for usage.

If ReadFile terminated normally, Success is set to TRUE, otherwise FALSE.

If no maximum size for ReadFile() has been specified, the OnFileRead()-event will not be fired.

OnFileWritten(Filename as String, Success as BOOLEAN) The OnFileWritten()-event is fired, after an previously initiated FileWrite() terminates.

The argument Filename is set to name of the file written. Success is set to to TRUE, if the operation terminated normally, otherwise false.

OnRead() Signals that data is available to be read from the socket.
OnReadTimeout() If the no incoming data arrives for a period of time specified by the property ReadTimeout, an OnReadTimeout() event is fired for this socket.
OnWrite() Signals that data can be written to the socket.

The event is initially fired after a successful connect or accept and everytime a socket becomes ready for writing again (after a WriteXxxxxxx()-operation returned with an error code EWOULDBLOCK (10035))

OnWriteTimeout() If the no data is written for a period of time specified by the property WriteTimeout, an OnWriteTimeout() event is fired for this socket.

 

Logfiles

Logfiles generated by MagicTCP! have the following structure:
SocketNumber / Action [/ optional TimeStamp] / printable TextData or IP address:port [ / optional hexadecimal representation of data]
Action code Corressponding action logged data
A Accept from remote host Remote IP address and port of accepted connection is logged
B Implicit or explicit bind to local socket Local IP address and port is logged
C Connect Remote IP address and port is logged
L Socket started to listen -
R Data read from socket Data read is logged, optional in hex representation
W Data written to socket Data written is logged, optional in hex representation
X Socket is closed -
Example:
0000 B 1999-07-22/12:21:02.570 0.0.0.0:5000
0000 L 1999-07-22/12:21:02.840 
0001 B 1999-07-22/12:21:02.900 127.0.0.1:1112
0001 C 1999-07-22/12:21:02.900 127.0.0.1:5000
0001 W 1999-07-22/12:21:02.900 If specified, an  49 66 20 73-70 65 63 69-66 69 65 64-2C 20 61 6E
                               y data sent over  79 20 64 61-74 61 20 73-65 6E 74 20-6F 76 65 72
                                this socket is   20 74 68 69-73 20 73 6F-63 6B 65 74-20 69 73 20
                               encrypted by thi  65 6E 63 72-79 70 74 65-64 20 62 79-20 74 68 69
                               s key. It may no  73 20 6B 65-79 2E 20 49-74 20 6D 61-79 20 6E 6F
                               t contain binary  74 20 63 6F-6E 74 61 69-6E 20 62 69-6E 61 72 79
                                nulls.           20 6E 75 6C-6C 73 2E
0000 A 1999-07-22/12:21:02.900 115.3.0.0:0
0002 R 1999-07-22/12:21:12.560 If specified, an  49 66 20 73-70 65 63 69-66 69 65 64-2C 20 61 6E
                               y data sent over  79 20 64 61-74 61 20 73-65 6E 74 20-6F 76 65 72
                                this socket is   20 74 68 69-73 20 73 6F-63 6B 65 74-20 69 73 20
                               encrypted by thi  65 6E 63 72-79 70 74 65-64 20 62 79-20 74 68 69
                               s key. It may no  73 20 6B 65-79 2E 20 49-74 20 6D 61-79 20 6E 6F
                               t contain binary  74 20 63 6F-6E 74 61 69-6E 20 62 69-6E 61 72 79
                                nulls.           20 6E 75 6C-6C 73 2E
0002 X 1999-07-22/12:21:12.890 
0000 X 1999-07-22/12:21:13.610 
0001 X 1999-07-22/12:21:13.610 

 

 


© Copyright 1999, MagicTCP!

Last updated on 30-Jul-1999

High energy for the internet!